﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Mapster;
using Furion.DatabaseAccessor.Extensions;

namespace LimaLims.Application.Service.Basic
{
    /// <summary>
    /// 模板服务
    /// </summary>
    [ApiDescriptionSettings(Name = "PrintTemplate", Order = 170)]
    [Route("api")]
    public class PrintTemplateService : IPrintTemplateService, IDynamicApiController, ITransient
    {
        private readonly IRepository<PrintTemplate> _printTemplateRep;  // 物料表仓储
        private readonly IRepository<ProductCategory> _productCategoryRep;  // 物料表仓储

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="PrintTemplateRep"></param>
        public PrintTemplateService(IRepository<PrintTemplate> PrintTemplateRep, IRepository<ProductCategory> productCategoryRep)
        {
            _printTemplateRep = PrintTemplateRep;
            _productCategoryRep = productCategoryRep;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("printTemplate/add")]
        public async Task Add(AddPrintTemplateInput input)
        {
            var isExist = await _printTemplateRep.DetachedEntities.AnyAsync(u => u.Name == input.Name );
            if (isExist)
                throw Oops.Oh("已存在相同名称的模板！");

            var printTemplate = input.Adapt<PrintTemplate>();

            await printTemplate.InsertAsync();
        }

        [HttpPost("printTemplate/delete")]
        public async Task Delete(long id)
        {
            var printTemplate = await _printTemplateRep.FirstOrDefaultAsync(u => u.Id == id);
            if (printTemplate == null)
                throw Oops.Oh("不存在此数据");

            var count = _productCategoryRep.DetachedEntities.Count(s => s.PrintTemplateId == id);

            if (count > 0)
            {
                throw Oops.Oh("已有产品分类正在使用当前模板，如需删除请先解除绑定关系！");
            }
            await printTemplate.DeleteAsync();
        }

        [HttpGet("printTemplate/detail")]
        public async Task<PrintTemplate> Detail(long id)
        {
            var printTemplate = await _printTemplateRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (printTemplate == null)
                throw Oops.Oh("不存在此数据");

            return printTemplate;
        }

        [HttpPost("printTemplate/edit")]
        public async Task Edit(EditPrintTemplateInput input)
        {
            var printTemplate = await _printTemplateRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (printTemplate == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _printTemplateRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同名称的模板！");

            var printTemplateModel = input.Adapt<PrintTemplate>();

            await printTemplateModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("printTemplate/selectList")]
        public async Task<List<SelectDto>> SelectList()
        {
            var list = await _printTemplateRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectDto
            {
                Value = x.Id,
                Label = x.Name
            }).ToList();
        }

        [HttpGet("printTemplate/page")]
        public async Task<PageResult<PrintTemplateOutput>> QueryPage([FromQuery] PrintTemplatePageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var items = await _printTemplateRep.DetachedEntities
                                         .Where((name, u => EF.Functions.Like(u.Name, $"%{input.SearchValue.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new PrintTemplateOutput
                                         {
                                             Id = u.Id,
                                             Name = u.Name,
                                             TemplateFile = u.TemplateFile,
                                             Remark = u.Remark,
                                             ValidStatus = u.ValidStatus,
                                             Sort = u.Sort,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return items;
        }
    }
}
